import WebIM from '@/common/HuanXinSdk/index.js'
import $tool from '@/common/Tools/index.js'

class HuanxinMixin {
	constructor(arg) {}
	// 注册环信
	Register(Json) {
		return new Promise((resolve, reject) => {
			let _Json = {
				apiUrl: WebIM.configsss.apiURL,
				username: Json.user,
				password: Json.pwd,
				nickname:'洋盘小主：'+ $tool.create_timeName(),
				appKey: WebIM.configsss.appKey,
				success: function(res) {
					resolve({
						msg: "ok",
						data: res
					})
				},
				error: function(e) {
					resolve({
						msg: "fail",
						data: e
					})
				}
			}
			WebIM.conn.registerUser(_Json)
		})
	}
	// 退出环信
	close() {
		WebIM.conn.close();
	}
	// 登录环信(账号密码登录)
	Login(Json) {
		return new Promise((resolve, reject) => {
			let _Json = {
				apiUrl: WebIM.configsss.apiURL,
				user: Json.user,
				grant_type: 'password',
				appKey: WebIM.configsss.appKey,
				success: function(res) {
					resolve({
						msg: "ok",
						data: res
					})
				},
				error: function(e) {
					resolve({
						msg: "fail",
						data: e
					})
				}
			}
			// 是token登录还是账号密码登录
			Json.accessToken ? _Json['accessToken'] = Json.accessToken : _Json['pwd'] = Json.pwd
			WebIM.conn.open(_Json)
		})
	}

	// 发送信息
	SendMessage(Json) {
		return new Promise((resolve, reject) => {
			let _Json = {
				msg: Json.msg, // 消息内容
				to: Json.to, // 接收消息对象（用户id）
				chatType: Json.chatType, // 设置为单聊
				success: function(id, serverMsgId) {
					resolve({
						msg: "ok",
						data: {
							id,
							serverMsgId
						}
					})
				},
				error: function(e) {
					resolve({
						msg: "fail",
						data: e
					})
				}
			}
			let id = WebIM.conn.getUniqueId();
			let messages = new WebIM.message(Json.SendType, id);
			messages.set(_Json);
			WebIM.conn.send(messages.body);
		})

	}
}
export default HuanxinMixin
